#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Last Update:

'''docstring
'''

__revision__ = '0.1'
__author__ = 'lxd'
import sys
sys.path.append('.')
sys.path.append('..')
import wx
import copy
import time
import tools
from threadWithQuit import ThreadWithQuit
from helper import main, question, farm, build
import timeThread
import pickle

class CaptureThread(ThreadWithQuit):
    def __init__(self,log,x0, y0, farmRecords, **kwargs):
        ThreadWithQuit.__init__(self, log)
        self.kwargs = kwargs
        self.x0, self.y0 = x0, y0
        self.farmRecords = farmRecords

    def run(self):
        from helper import farmCapture
        cap = farmCapture.WebCapture(self.log,self.x0, self.y0, **self.kwargs)
        pc = cap.getCapture()
        if pc:
            response = ''
            for ts,buf in pc:
                self.checkSet()
                stream = cap.getWholeStream(buf)
                if stream:
                    if (stream[:4] == 'HTTP') and (response != ''):
                        body = cap.processZip(response)
                        record = cap.parse(body)
                        if record:
                            self.farmRecords.append(record)
                        response = ''
                    response += stream

class WorkThread(ThreadWithQuit):
    def __init__(self,window, **kwargs):
        ThreadWithQuit.__init__(self, window.log)
        self.window = window
        self.dm = window.dm
        self.kwargs= kwargs
        self.canAnswer = kwargs.get('canAnswer', True)
        self.canFarm = kwargs.get('canFarm', True)
        self.canCapture = kwargs.get('canCapture', False)
        self.canBuild = kwargs.get('canBuild', False)
        self.farmAction = kwargs.get('farmAction', 0)
        self.buildUpdates = kwargs.get('buildUpdates', [])

    def run(self):
        def _getMainAndHelper():
            self.main = main.Helper(self.log, self.dm)
            return self.main.checkMainPage()

        self.log.debug('start work')
        self.timeWorks = timeThread.TimeWorks()
        if _getMainAndHelper():
            self.work()
            self.log.debug('work over')
        self.log.debug('done')

    def work(self):
        if self.canAnswer:self.doAnswerAction()
        if self.canFarm:self.doFarmAction()
        if self.canBuild:self.doBuildAction()
        #TODO:放到每个大的间隙
        self.checkWaitWork()

    def checkWaitWork(self):
        data = self.timeWorks.checkTimeThread()
        if data:
            if data['kind'] == 'build':
                if self.canBuild:self.doBuildAction()
            elif data['kind'] == 'farm':
                pass
                #farm_something(data)

##########辅助函数##########
    def waitWhenLoad(self):
        """如果出现“正在加载”提示框则等候
        """
        while self.main.findLoading():
            self.checkSet()
            time.sleep(1)

    def checkSet(self):
        """随时停止信号量。
        在循环里或等待网络返回等耗时的工作前使用
        """
        #TODO:可能不用重载这个函数，主线程退出应该capture也会退出，需要测试
        if self.timeToQuit.isSet():
            if hasattr(self, 'capture'):
                if self.capture.isAlive():
                    self.capture.stop()
            self.log.debug('main thread exit')
            sys.exit()
##########farm##########
    def createCapture(self, dm):
        if self.canCapture:
            self.farmRecords = []
            self.capture = CaptureThread(self.log, dm.origin_x, dm.origin_y, self.farmRecords, **self.kwargs)
            self.capture.setDaemon(True) 
            self.capture.start()

    def doFarmAction(self):
        def getCenter():
            """得到原点
            """
            center = self.main.getFarmCenterPos()
            if center:
                origin_x = center[0] + 442
                origin_y = center[1] - 70
                self.farm.dm.setCenterPos(origin_x, origin_y)
            return center
        def water():
            self.farm.selectFriendList()
            self.farm.gotoFriend()
            while True:
                self.checkSet()
                for i in range(12):
                    self.checkSet()
                    self.farm.clickIfNeedWater(i)
                if not self.farm.clickNextPage():
                    break
        def _steal():
            crops= self.farm.getStealCrops()
            if crops:
                for crop in crops:
                    self.checkSet()
                    if self.farmAction > 0:
                        self.farm.dm.click(crop)
                        self.farmAction -= 1

        @tools.loopWithTime(self.checkSet)
        def _steal_capture():
            if self.farmRecords:
                for crop in self.farmRecords[0]['points']:
                    self.checkSet()
                    if self.farmAction > 0:
                        self.farm.dm.click(crop)
                        self.farmAction -= 1
                self.farmRecords= []
                return True
            else:
                return False

        def steal():
            self.farm.selectFriendList()
            self.farm.gotoEmery()
            #self.farm.gotoFriend()
            hasAction = True
            while hasAction:
                self.checkSet()
                for i in range(12):
                    self.checkSet()
                    if self.farmAction > 0:
                        if self.farm.canSteal(i):
                            self.farm.clickStealTool()
                            if not self.canCapture:
                                _steal()
                            else:
                                _steal_capture()
                    else:
                        self.log.info(u'没有可用的行动力了')
                        hasAction = False
                        break
                if hasAction:
                    if not self.farm.clickNextPage(): break
        self.log.debug('start farm work')
        dm = copy.copy(self.dm)
        self.farm= farm.Helper(self.log,dm, **self.kwargs)

        self.main.clickFarmModel()
        self.waitWhenLoad()
        if getCenter():
            self.createCapture(self.farm.dm)
            self.farm.doMyself()
            water()
            steal()
            self.main.closeWidgets()
        if hasattr(self, 'capture') and self.capture:
            self.capture.stop()
        self.log.debug('end farm work')
        del self.farm

##########answer##########
    def doAnswerAction(self):
        """自动答题
        """
        @tools.loopWithTime(self.checkSet)
        def findAnswerModel():
            """不停的找答题人
            """
            return self.main.clickAnswerModel()

        def answerQuestions():
            """不停地回答问题
            """
            while True:
                self.checkSet()
                self.question.getQuestionAndAnswers()
                self.question.processAnswer()
                time.sleep(1)
                if not self.question.checkAnswer():
                    break
                self.question.clickNext()

        def getCenter():
            """得到原点
            """
            center = self.main.getQuestionCenterPos()
            if center:
                self.question.dm.setCenterPos(center)
            return center

        self.log.debug('start answer')
        dm = copy.copy(self.dm)
        self.question= question.Helper(self.log,dm)
        while True:
            self.checkSet()
            findAnswerModel()
            self.waitWhenLoad()
            if not getCenter():break
            if self.question.canAnswer():
                self.question.clickSuperQuestion()
                answerQuestions()
                self.main.closeWidgets()
            else:
                break
        self.main.closeWidgets()
        self.log.debug('answer over')
        del self.question

##########build##########
    def doBuildAction(self):
        def doBuild(num):
            """建造num个建筑
            """
            for b in self.buildUpdates:
                self.checkSet()
                self.build.dm.initCenterPos()
                self.log.debug('build:%s' %str(b))
                self.log.debug('origin_pos:(%s, %s)' %(self.dm.origin_x, self.dm.origin_y))
                if self.build.findBuild(b):#顺便定下了原点
                    self.log.debug('find build success')
                    if self.build.clickBuild(b):
                        num -= 1
                        if num <= 0:
                            break
            else:
                self.log.debug('build not enough, should set up %s more' %num)

        def saveBuilds():
            self.kwargs.update({'buildUpdates':self.buildUpdates})
            data = pickle.dumps(self.kwargs)
            tools.saveData(config.user_file, data)

        self.log.debug('start build')
        dm = copy.copy(self.dm)
        self.build= build.Helper(self.log, dm, self.main, self.timeWorks)

        canNum = 1
        while canNum:
            canNum = self.build.getCanBuildNum()
            self.build.recordBuildTimes()
            if canNum>0:
                doBuild(canNum)
                saveBuilds()

        self.log.debug('build over')
        del self.build

if __name__ == '__main__':
    import config
    import dmsoft
    import bin
    class TestBindFlash(bin.BindFlash):
        """测试用，直接作用于浏览器中的游戏
        """
        def getFlashHwnd(self):
            return True

    class MainFrame(wx.Frame):
        def __init__(self, log):
            wx.Frame.__init__(self, None, -1)
            self.log = log
            self.dm = dmsoft.dm
            self.work()

        def work(self):
            b = TestBindFlash(self.log, self.dm)
            if b.bind():
                data = config.data
                work = WorkThread(self, **data)
                work.setDaemon(True) 
                work.start()

    app = wx.PySimpleApp()
    MainFrame(config.log).Show()
    app.MainLoop()

